# encoding: utf-8

import numpy as np
import pandas as pd
import cv2
import math
import matplotlib.pyplot as plt
import pywt
import os


def bilinear(src_img, dst_shape):
    """
    双线性插值法,来调整图片尺寸

    :param org_img: 原始图片
    :param dst_shape: 调整后的目标图片的尺寸
    :return:    返回调整尺寸后的图片矩阵信息
    """
    dst_img = np.zeros((dst_shape[0], dst_shape[1], 3), np.uint8)
    dst_h, dst_w = dst_shape
    src_h = src_img.shape[0]
    src_w = src_img.shape[1]
    # i：纵坐标y，j：横坐标x
    # 缩放因子，dw,dh
    scale_w = src_w / dst_w
    scale_h = src_h / dst_h

    for i in range(dst_h):
        for j in range(dst_w):
            src_x = float((j + 0.5) * scale_w - 0.5)
            src_y = float((i + 0.5) * scale_h - 0.5)

            # 向下取整，代表靠近源点的左上角的那一点的行列号
            src_x_int = math.floor(src_x)
            src_y_int = math.floor(src_y)

            # 取出小数部分，用于构造权值
            src_x_float = src_x - src_x_int
            src_y_float = src_y - src_y_int

            if src_x_int + 1 == src_w or src_y_int + 1 == src_h:
                dst_img[i, j, :] = src_img[src_y_int, src_x_int, :]
                continue
            dst_img[i, j, :] = (1. - src_y_float) * (1. - src_x_float) * src_img[src_y_int, src_x_int, :] + \
                               (1. - src_y_float) * src_x_float * src_img[src_y_int, src_x_int + 1, :] + \
                               src_y_float * (1. - src_x_float) * src_img[src_y_int + 1, src_x_int, :] + \
                               src_y_float * src_x_float * src_img[src_y_int + 1, src_x_int + 1, :]
    return dst_img


def signal_to_TFRs():
    sampling_rate = 2560 - 1  # 采样频率
    t = np.arange(0, 0.1, 0.1 / sampling_rate)  # 0.1为单样本持续时间
    wavename = "cgau8"
    totalscal = 10000
    fc = pywt.central_frequency(wavename)  # 中心频率
    cparam = 2 * fc * totalscal
    scales = cparam / np.arange(totalscal, 1, -1)

    dir_path = '/home/zxl/zy/IIOT_model/Data/PHM12_Bearing/Bearing1_3'
    path_list = os.listdir(dir_path)
    path_list.sort()
    # print(path_list)
    idx = 1
    for filename in path_list:
        data_signal = pd.read_csv('/home/zxl/zy/IIOT_model/Data/PHM12_Bearing/Bearing1_3/'+filename)
        data_signal = data_signal.values[:, 4]
        [cwtmatr, frequencies] = pywt.cwt(data_signal, scales, wavename, 1.0 / sampling_rate)  # 连续小波变换
        plt.contourf(t, frequencies, abs(cwtmatr))
        plt.ylabel(u"Frequency(Hz)")
        plt.xlabel(u"Time(s)")
        plt.axis('off')
        plt.gca().xaxis.set_major_locator(plt.NullLocator())
        plt.gca().yaxis.set_major_locator(plt.NullLocator())
        plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
        plt.margins(0, 0)
        plt.savefig('/home/zxl/zy/IIOT_model/Data/PHM12_Bearing/Bearing1_3_TFRs/' + str(idx) + '_TFR.jpg')
        plt.show()

        src = cv2.imread('/home/zxl/zy/IIOT_model/Data/PHM12_Bearing/Bearing1_3_TFRs/' + str(idx) + '_TFR.jpg',
                         cv2.IMREAD_COLOR)
        # src_shape = (src.shape[0], src.shape[1])
        dst_shape = (30, 30)  # 定义图片缩放后的尺寸
        # 自定义的图像放缩函数
        dst_img = bilinear(src, dst_shape)
        cv2.imwrite('/home/zxl/zy/IIOT_model/Data/PHM12_Bearing/Bearing1_3_BilineINTERs/' + str(idx) + '_BI.jpg', dst_img)

        idx += 1


if __name__ == '__main__':
    '''
    img_path = 'D:/MyPycharm/IIOT_model/Utils/test.jpg'

    src = cv2.imread(img_path, cv2.IMREAD_COLOR)
    # 高337 - 宽500
    src_shape = (src.shape[0], src.shape[1])
    # 定义图片缩放后的尺寸
    dst_shape = (30, 30)

    # 图像放缩均采用双线性插值法
    # opencv的放缩图像函数
    # resize_image = cv2.resize(src, (100, 400), interpolation=cv2.INTER_LINEAR)

    # 自定义的图像放缩函数
    dst_img = bilinear(src, dst_shape)

    # cv2.imwrite('D:/MyPycharm/IIOT_model/Utils/1_new_resize.jpg', resize_image)
    cv2.imwrite('D:/MyPycharm/IIOT_model/Utils//1_new.jpg', dst_img)
    '''

    signal_to_TFRs()
